package com.liu.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageProducer;
import org.apache.activemq.AsyncCallback;

import javax.jms.*;
import java.util.UUID;

public class JmsProduce {

    public static final String ACTIVEMQ_URL = "tcp://192.168.25.133:61616";
    public static final String QUEUE_NAME = "queue01";

    public static void main(String[] args) throws JMSException {
        //1.创建连接工厂,按照给定的url地址访问
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂，获得连接connection并启动
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //创建会话,两个参数：第一个事务、第二个签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建目的地(是队列还是主题)
        Destination queue = session.createQueue(QUEUE_NAME);//Conllection c = new ArrayList()

        //创建消息生产者
        ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue);

        //        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);//非持久化
//        producer.setDeliveryMode(DeliveryMode.PERSISTENT);//持久化
        /**
         * MQ信息持久化
         *      producer.setDeliveryMode(参数为1时不持久化，为2时进行持久化)
         *      ActiveMQ默认的持久化策略是持久化
         */

        //发送消息，使用MessageProducer发送三条消息但MQ队列里
        for (int i = 0; i < 3; i++) {
//            TextMessage textMessage = session.createTextMessage("msg----" + i);//一个字符串
            MapMessage mapMessage = session.createMapMessage();
            mapMessage.setStringProperty("count", Integer.toString(i));//设置信息属性，添加信息识别度
            mapMessage.setString("k1", "v" + i);
            //通过消息生产者发送
            mapMessage.setJMSMessageID(UUID.randomUUID().toString() + "---orderLiu");
            final String id = mapMessage.getJMSCorrelationID();
            producer.send(mapMessage, new AsyncCallback() {
                public void onSuccess() {
                    System.out.println(id + "has been ok");
                }

                public void onException(JMSException e) {
                    System.out.println(id + "has been no");
                }
            });
        }

        //关闭资源
        session.close();
        connection.close();

        System.out.println("MQ信息发送完毕");

    }
}
